//导入用户构造函数
const {
    User
} = require('../../model/users')

module.exports = async (req, res, next) => {

    //获取用户传递过来的id和新地址
    let addNewForm = req.body
    //根据这个id查询数据
    const user = await User.findOne({
        userId: addNewForm.userId
    })
    if (user) {
        //查询成功
        // 自动生成地址编号
        let platForm = '1000'
        let r1 = Math.floor(Math.random() * 10)
        let r2 = Math.floor(Math.random() * 10)
        let r3 = Math.floor(Math.random() * 10)
        let r4 = Math.floor(Math.random() * 10)
        let addressId = platForm + r1 + r2 + r3 + r4

        // console.log(max)
        let address = {
            addressId,
            userName: addNewForm.userName,
            streetName: addNewForm.streetName,
            postCode: addNewForm.postCode,
            tel: addNewForm.tel,
            isDefault: false
        }
        //把这个对象追加到user.addressList
        user.addressList.push(address)
        user.save()
        res.json({
            status: 200,
            msg: '添加成功',
            data: {
                addressList: user.addressList
            }
        })
    } else {
        res.json({
            status: 400,
            msg: '添加失败，请确认登陆状态!!!',
            data: ''
        })
    }
}